﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SocialPlatforms;
using Yoozoo.UI.YGUI;

public class ReddotNodeItem : MonoBehaviour
{
    public string m_path;
    [SerializeField] private int maxRedDotNum;
    private YText m_text;
    private ReddotNode m_node;
    /// <summary>
    /// Cached for speed
    /// </summary>
    private YText CacheText
    {
        get
        {
            if (ReferenceEquals(m_text, null))
            {
                m_text = GetComponentInChildren<YText>();
            }

            return m_text;
        }
    }
    void OnEnable()
    {
        AddToNode();
    }

    public void SetPath(string path)
    {
        if (m_path == path)
        {
            return;
        }

        if (m_node != null)
        {
            m_node.RemoveNodeItem(this);
            m_node = null;
        }

        m_path = path;
        
        if (string.IsNullOrEmpty(m_path))
        {
            return;
        }
        
        //防止ReddotNodeItem所在的对象一开始就设置成了隐藏状态
        //所以在设置路径后 将所在对象显示出来 后面由数据控制
        transform.SetActive(true);

        AddToNode();
    }
    
    public void SetValue(int value)
    {
        bool active = value >= 1;
        transform.SetActive(active);
        if (active && CacheText != null)
        {
            if (this.maxRedDotNum > 0 && value > this.maxRedDotNum)
                CacheText.text = string.Format("{0}+", this.maxRedDotNum);
            else
                CacheText.text = value.ToString();
        }
    }

    public void AddToNode()
    {
        if (!isActiveAndEnabled || string.IsNullOrEmpty(m_path))
        {
            return;
        }
        
        ReddotNode newNode = ReddotManager.GetInstance("").GetNode(m_path);
        if (m_node == newNode)
        {
            return;
        }
        
        m_node?.RemoveNodeItem(this);
        m_node = newNode;
        if (m_node != null)
        {
            m_node.AddNodeItem(this);
        }
        else
        {
            UnityEngine.Debug.LogWarning($"[红点系统] AddToNode 不存在节点:{m_path}");
        }
    }

    public void RemoveFromNode()
    {
        if (m_node != null)
        {
            m_node.RemoveNodeItem(this);
        }
        else
        {
            UnityEngine.Debug.LogError($"[红点系统] RemoveFromNode 不存在节点:{m_path}");
        }
    }
    

    void OnDestroy()
    {
        m_node?.RemoveNodeItem(this);
    }
}
